package com.wwg.myapplication;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.skg.tools.MyWindowManager;
import com.skg.tools.R;
import com.skg.tools.utils.BitmapUtils;
import com.skg.tools.view.StrokeTextView;

public class ProtectBurnView2 extends LinearLayout {

    private static final int ANIMTIME = 2000;
    private static final int ANIM_TYPE_STOP = 1;
    //    private static final int ANIM_TYPE_CONTENT = 2;
    private static final int ANIM_TYPE_START = 2;
    private final String TAG = "ProtectBurnView2";
    private Context mContext;
    private ImageView imageView;
    private EnterAnimLayout anim_layout;

    // 添加全局事件监听
    private void registerInputListener() {
        getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            View rootView = getRootView();
            rootView.setOnTouchListener((v, event) -> {
                if (animRipple != null && animRipple.isAnimationRunning()) {
                    cancelPendingAnimations();
                    MyWindowManager.removeBurnView(mContext);
                    return true;
                }
                return false;
            });

            rootView.setOnKeyListener((v, keyCode, event) -> {
                if (animRipple != null && animRipple.isAnimationRunning()) {
                    cancelPendingAnimations();
                    MyWindowManager.removeBurnView(mContext);
                    return true;
                }
                return false;
            });
        });
    }
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // case ANIM_TYPE_CONTENT:
                //     anim_layout.setBackgroundColor(Color.TRANSPARENT);
                //     imageView.setVisibility(GONE);
                //     if (bitmap != null) {
                //         imageView.setImageBitmap(bitmap);
                //         imageView.setVisibility(VISIBLE);
                //         anim_layout.setAnim(animRipple);
                //         animRipple.startAnimation(10000);
                //     }

                //     mHandler.sendEmptyMessageDelayed(ANIM_TYPE_STOP, 10000);
                //     break;
                case ANIM_TYPE_STOP:
                    // 增加动画状态检查
//                    if (animRipple != null && animRipple.isAnimationRunning()) {
//                        mHandler.sendEmptyMessageDelayed(ANIM_TYPE_STOP, 500);
//                    } else {
//                        MyWindowManager.removeBurnView(mContext);
//                    }
//                    break;
                case ANIM_TYPE_START:
                    startAnim();
                    break;
            }
        }
    };
    private AnimRipple animRipple;
    private Bitmap bitmap;
    private StrokeTextView protectburn_title;
    private boolean isAnimationStarted = false; // 标记动画是否已启动

    public ProtectBurnView2(Context context) {
        super(context);
        mContext = context;
        init();
    }

    public ProtectBurnView2(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();
    }

    public ProtectBurnView2(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }

    public ProtectBurnView2(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        mContext = context;
        init();
    }

    private void init() {
        LayoutInflater.from(mContext).inflate(R.layout.view_layout, this);
        initView();
        // 设置根布局点击监听
        setOnClickListener(v -> {
            cancelPendingAnimations();
            MyWindowManager.removeBurnView(mContext);
        });

        new Thread(() -> {
            bitmap = BitmapUtils.getBitmap(mContext);
            post(() -> {
                if (bitmap != null) {
                    imageView.setImageBitmap(bitmap);
                    imageView.setAlpha(0.95f);
                }
            });
        }).start();

        // 确保在布局完成后启动动画
        post(() -> {
            if (getWidth() > 0 && getHeight() > 0) {
                mHandler.removeMessages(ANIM_TYPE_START);
                mHandler.sendEmptyMessage(ANIM_TYPE_START);
            } else {
                addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
                    if (right - left > 0 && bottom - top > 0) {
                        mHandler.removeMessages(ANIM_TYPE_START);
                        mHandler.sendEmptyMessage(ANIM_TYPE_START);
                    }
                });
            }
        });
        registerInputListener(); // 添加全局监听

    }

    private void initView() {
        imageView = this.findViewById(R.id.image);
        anim_layout = findViewById(R.id.anim_layout);
        protectburn_title = findViewById(R.id.protectburn_title); // 获取文字视图

        // 初始设置
        protectburn_title.setAlpha(0f); // 确保初始透明
        protectburn_title.setVisibility(VISIBLE); // 但保持可见（透明状态）
    }

    private void initBitmap() {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            Log.e(TAG, "startJudgeProjectMode error = " + e.getMessage());
        }
        bitmap = BitmapUtils.getBitmap(mContext);
    }

    private void startAnim() {
        imageView.setVisibility(VISIBLE);
        if (animRipple == null) {
            animRipple = new AnimRipple(anim_layout, protectburn_title);
            anim_layout.setAnim(animRipple);
            protectburn_title.setAlpha(0f);
        }

        if (!anim_layout.ismIsAnimaionRun()) {
            animRipple.startAnimation(20000); // 保持10秒完整动画

            // 仅在动画自然结束时检查停止
            mHandler.sendEmptyMessageDelayed(ANIM_TYPE_STOP, 20500); // 比动画多500ms缓冲
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (bitmap != null) {
            bitmap.recycle();
            bitmap = null;
        }
    }
    // 添加取消动画方法
    public void cancelPendingAnimations() {
//        mHandler.removeMessages(ANIM_TYPE_CONTENT);
        mHandler.removeMessages(ANIM_TYPE_STOP);
        mHandler.removeMessages(ANIM_TYPE_START);

        if (animRipple != null) {
            animRipple.cancelAnimation();
        }
    }

    public void reset() {
        if (animRipple != null) {
            animRipple.reset();
        }
        if (bitmap != null) {
            bitmap.recycle();
            bitmap = null;
        }

        // 重置文字视图状态
        if (protectburn_title != null) {
            protectburn_title.setAlpha(0f);
        }

        // 重置布局状态
        if (anim_layout != null) {
//            anim_layout.reset();
        }
    }
/*    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        // 确保布局完成后再启动动画
        if (w > 0 && h > 0) {
            mHandler.removeMessages(ANIM_TYPE_START);
            mHandler.sendEmptyMessage(ANIM_TYPE_START);
        }
    }*/


}
